package com.service1.controller

import com.base.model.Model_Redis
import com.base.model.Model_Service1
import com.base.model.Model_Service2
import com.base.service.IRPC_Service1
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand
import com.service1.db.mongodb.service.MongoDBService
import com.service1.db.mybatis.db1.service.MyBatisDB1Service
import com.service1.db.mybatis.db2.service.MyBatisDB2Service
import com.service1.db.redis.RedisService
import com.service1.rpc.RPC_Service2
import com.yfree.global.YController
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.client.RestTemplate

@RestController
@DefaultProperties(defaultFallback = "yfree_defaultFallback")
class Controller_Service1 : YController(), IRPC_Service1 {
    @Autowired
    lateinit var myBatisDB1Service: MyBatisDB1Service

    @Autowired
    lateinit var myBatisDB2Service: MyBatisDB2Service

    @Autowired
    lateinit var redisService: RedisService

    @Autowired
    lateinit var mongoDBService: MongoDBService

    @Autowired
    lateinit var restTemplate: RestTemplate

    @Autowired
    lateinit var rpc_Service2: RPC_Service2

    @Value("\${server.port}")
    private lateinit var serverPort: String

//    @Autowired
//    lateinit var discoveryClient: DiscoveryClient

    @HystrixCommand
    override fun callService2_rest(): String {
        // val instances = discoveryClient.getInstances("service2") // 别名获取集群
        val service2Result = restTemplate.getForObject("http://service2/service2/api", String::class.java)
        val yModel = fromJson(service2Result, Model_Service2::class.java)
        return json(result = listOf(
                Model_Service1("Server1Port:$serverPort,${yModel.root.result[0].value}")
        ))
    }

    @HystrixCommand
    override fun callService2_feign(): String {
        val service2Result = rpc_Service2.api()
        val yModel = fromJson(service2Result, Model_Service2::class.java)
        return json(result = listOf(
                Model_Service1("Server1Port:$serverPort,${yModel.root.result[0].value}")
        ))
    }

    @HystrixCommand
    @Transactional
    override fun db_MySQL(id: String): String {
        return json(result = myBatisDB1Service.find(id) + myBatisDB2Service.find(id))
    }

    @HystrixCommand
    @Transactional
    override fun db_MongoDB(id: String): String {
        return json(result = listOf(
                mongoDBService.find(id)
        ))
    }

    @HystrixCommand
    @Transactional
    override fun db_Redis(id: String): String {
        redisService.saveID(id)
        return json(result = listOf(
                Model_Redis(redisService.readID())
        ))
    }
}
